package com.dyz.leetcode._19_greedy;

import java.util.ArrayDeque;
import java.util.Deque;

public class _1209_removeDuplicates {
    class Pair{
        int cnt;
        char ch;
        Pair(char ch, int cnt){
            this.ch = ch;
            this.cnt = cnt;

        }
    }
    public String removeDuplicates(String s, int k) {
        Deque<Pair> stack = new ArrayDeque<>();
        for (int i = 0; i < s.length(); i++) {
            if(stack.isEmpty() || s.charAt(i)!=stack.peek().ch){
                stack.push(new Pair(s.charAt(i), 1));
            }else {
                stack.peek().cnt++;
                if(stack.peek().cnt==k){
                    stack.pop();
                }
            }

        }
        StringBuilder sb= new StringBuilder();
        while (!stack.isEmpty()){
            Pair p = stack.pollLast();
            for(int i=0; i<p.cnt; i++){
                sb.append(p.ch);
            }
        }
        return sb.toString();
    }
}
